var Database = require('../app/database');
var util = require('util');

var Router = module.exports = {};
Router.Routes = new Array();

log = function(msg) {
    //console.log(new Date().toLocaleTimeString() + ' [router]: ' + msg);
};

Router.add = function(route){
	Router.Routes.push(route);
	return this;
};
Router.Methods = {};
Router.Methods.GET = 'GET';
Router.Methods.POST = 'POST';
Router.Methods.PUT = 'PUT';
Router.Methods.DELETE = 'DELETE';

Router.Access = {};
Router.Access.Public = 0;
Router.Access.Registered = 1;
Router.Access.User = 2;
Router.Access.Owner = 4;
Router.Access.Admin = 8;

var registerAPI = function (app, api) {
    log('Register API: ' + util.inspect(api, false, null))
	var methods = {
		'GET':function(app,api){
            var auth = api.Authorize;
			app.get('/api/' + api.URL,setSession,function(req, res, next){authorize(req,res,next,auth)},api.Handler);
		},
		'POST':function(app,api){
            var auth = api.Authorize;
			app.post('/api/' + api.URL,setSession,function(req, res, next){authorize(req,res,next,auth)},api.Handler);
		},
		'PUT':function(app,api){
            var auth = api.Authorize;
			app.put('/api/' + api.URL,setSession,function(req, res, next){authorize(req,res,next,auth)},api.Handler);
		},
		'DELETE':function(app,api){
            var auth = api.Authorize;
			app.delete('/api/' + api.URL,setSession,function(req, res, next){authorize(req,res,next,auth)},api.Handler);
		},
	};
	if (methods[api.Method]) {
		return methods[api.Method](app,api);
	} else {
		return methods.GET(app.api);
	};
};

Router.register = function(app) {
	// REST Calls coming from the different routes
    for (index = 0; index < Router.Routes.length; ++index) {
		registerAPI(app,Router.Routes[index]);
	};
};

var authorize = function(req,res,next,access){
	var hasAccess = false;
    var role = (req.session.user && req.session.user.role) ? req.session.user.role : 0;
	log('checkAuthorization(' + access + '/' + role + '): ' + util.inspect(req.session,false,null));
	if (access <= 0) {
		hasAccess = true;
	} else if (role >= access) {
		hasAccess = true;
	};
	if (hasAccess) {
		next();
	} else {
	    log('Unauthorized(' + access + '): ' + hasAccess + ' - Role:' + role);
		res.send(401,{status:401, message: 'Unauthorized access', type:'internal'});
	};
};

var setSession = function(req,res,next){
	log('setSession:' + util.inspect(req.session,false,null));
	req.session.lastPage = req.originalUrl || '';
	if (req.session.user) {
		req.session.user.role = req.session.user.role || 0;
	} else {
		req.session.user = {};
		req.session.user = new Database.Models.User({password:'', role: 0});
	};
	log('setSession end: ' + util.inspect(req.session,false,null));
	next();
};